<!--  -->
<template>
  <div class="page-classify">
    <!-- <router-link to="/city">当前选择的城市是：{{ curCityName }}</router-link> -->

    <normal-header title="分类"></normal-header>

    <header-type :types="types"  @click="onTypeChange"></header-type>

    <div class="classify-main">
      <!-- 传给子组件的数据应该是计算属性中的cartoonList -->
      <cartoon-list :list="cartoonList"></cartoon-list>
    </div>
  </div>
</template>

<script>
import NormalHeader from '@/components/NormalHeader'
import HeaderType from '@/components/HeaderType'
import CartoonList from '@/components/CartoonList'
import { getTypes, getTypeList } from '@/api/cartoon'
import { unformat } from '@/utils/apiHeader'

export default {
  name: 'Classify',
  components: {
    NormalHeader,
    HeaderType,
    CartoonList
  },

  data() {
    return {
      types: [],
      // 分类数据
      classifyList: []
    }
  },

  computed: {
    // 处理同一个组件(分类页面和排行榜页面组件一样)的数据匹配问题，
    // 因为在分类页面接口数据的名字和排行榜页面接口数据的名字不一样，
    cartoonList () {
      // 统一处理后再传给排行榜页面，[{bigbook_id, bigbook_name, }] => [{id, name}]
      return this.classifyList.map(item => {
        return {
          // 子组件接口获取的数据名字就统一改为了name、coverURL、id、author、view
          id: item.bigbook_id,
          coverurl: item.coverurl,
          name: item.bigbook_name,
          author: item.bigbook_author,
          view: item.bigbookview
        }
      })
    }
  },

  methods: {
    getTypes() {
      return getTypes().then(res => {
        this.types = res.info
      })
    },

    getTypeList(subject) {
      getTypeList(subject).then(res => {
        // 对 res.info 做解密, 并解析成 JSON
        const info = JSON.parse(unformat(res.info))
        console.log(info)
        this.classifyList = info.comicsList
      })
    },

    /**
     * 切换分类类型时，触发
     */
    onTypeChange (payload) {
      console.log(payload)
      // 取出 payload 中的 type 中的 targetargument
      const subject = payload.type.targetargument
      // 从新发送 B 接口请求
      this.getTypeList(subject)
    }
  },

  async created() {
    // A B 两个接口，B 接口的参数需要从 A 接口的返回值中去获取。要如何办？
    await this.getTypes()
    this.getTypeList(this.types[0].targetargument)
  }
}
</script>
<style lang="less" scoped>
.page-classify {
  display: flex;
  flex-direction: column;
  height: 100%;

  .classify-main {
    flex: 1;
    overflow-y: auto;
  }
}
</style>
